import 'dart:convert';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class DataFormatUtils {
// contains(var)：判断字符串是否包含var
// subString()：字符串截取
// startsWith(var)：判断字符串是否以var的字符串起始
// endsWith(var)：判断字符串是否以var的字符串结束
// indexOf(var)：获取var在字符串的第一个位置索引值，如果没找到返回-1
// lastIndexOf()：获取var在字符串的倒序第一个位置的索引值，如果没找到返回-1，
// toLowerCase()：将字符串小写处理
// toUpperCase()：将字符串大写处理
// trim():将字符串两边去除空格处理
// trimLeft():将字符串的左边空格去除
// trimRight():将字符串的右边空格去除
// split(var)：将字符串按照var分割成数组

  static const USERNAME_EMAIL_MAX_LENGTH = 50;

  ///
  /// 格式化国家/地区码，不足4位前面补0
  ///
  static String formatAreaCode(String areaCode) {
    return areaCode.padLeft(4, '0');

    // 方式二
    // int code = int.parse(areaCode);
    // NumberFormat formatter = NumberFormat("0000");
    // return formatter.format(code);
  }

  ///
  /// 根据国家码和手机号获取完整的手机号（后台所需格式 008613100000000）
  /// areaCode: 国家码 86
  /// phone: 手机号 13100000000
  ///
  static String getCompletePhone(String areaCode, String phone) {
    return areaCode.padLeft(4, '0') + phone;
  }

  /// 获取国家码
  /// areaCodePhone: 0086131xxxxxxxx
  /// 返回格式：86
  static String getAreaCode(String? areaCodePhone) {
    int count = 4;
    if (areaCodePhone == null || areaCodePhone.length < count) {
      return '';
    }
    String areaCode = areaCodePhone.substring(0, 4);

    int index = 0;
    for (var i = 0; i < count; i++) {
      if (areaCode.substring(i, i + 1) != '0') {
        index = i;
        break;
      }
    }
    return areaCode.substring(index, count);
  }

  /// 获取国家码（去除前面的0）
  /// areaCode: 0086
  /// 返回格式：86
  static String getAreaCodeExceptZero(String? areaCode) {
    if (areaCode == null) {
      return '';
    }
    int index = 0;
    for (var i = 0; i < 4; i++) {
      if (areaCode.substring(i, i + 1) != '0') {
        index = i;
        break;
      }
    }
    return areaCode.substring(index, 4);
  }

  /// 获取手机号
  /// areaCodePhone: 0086131xxxxxxxx
  /// 返回格式：13100000000
  static String getPhone(String? areaCodePhone) {
    int count = 4;
    if (areaCodePhone == null || areaCodePhone.length < count) {
      return '';
    }
    return areaCodePhone.substring(4, areaCodePhone.length);
  }

  /// 获取国家码+隐私手机号
  /// areaCodePhone: 0086131xxxxxxxx
  /// showSecret: 中间是否显示星号*
  /// 返回格式：+86 131****1234
  static String getAreaAndPhone(String? areaCodePhone, {bool? showSecret}) {
    if (!isAvailableString(areaCodePhone)) {
      return '';
    }
    String areaCode = getAreaCode(areaCodePhone);
    String phone = getPhone(areaCodePhone);

    if (showSecret == true) {
      String privacyPhone = phone.replaceFirst(RegExp(r'\d{4}'), '****', 3);
      return '+$areaCode $privacyPhone';
    }
    return '+$areaCode $phone';
  }

  /// 获取密文邮箱
  /// areaCodePhone: inmotion@imscv.com
  /// 返回格式：i*****n@imscv.com
  static String getSecretEmail(String? email) {
    if (!isAvailableEmail(email)) {
      return '';
    }
    List<String> strs = email!.split("@");
    String prefix = strs.first;
    if (prefix.length > 2) {
      // 中间位补*，最多8位
      int symbolCount = min(prefix.length - 2, 8);
      prefix = '${prefix.substring(0, 1)}${getSymbolWithCount(symbolCount)}${prefix.substring(prefix.length - 1, prefix.length)}';
    }
    return prefix + '@' + strs.last;
  }

  /// 获取一定数量的*
  static getSymbolWithCount(int count) {
    String symbol = '';
    for (var i = 0; i < count; i++) {
      symbol += '*';
    }
    return symbol;
  }

  ///
  /// 去除字符串首位空格
  ///
  static String removeLeadingAndTrailingSpaces(String string) {
    return string.trim();
  }

  ///
  /// 去除字符串所有空格
  ///
  static String removeAllSpaces(String string) {
    return string.replaceAll(new RegExp(r"\s+\b|\b\s"), "");
  }

  ///
  /// 判断是否为可用字符串
  ///
  static bool isAvailableString(Object? object) {
    if (object != null && object is String && object.isNotEmpty) {
      return true;
    }
    return false;
  }

  ///
  /// 判断是否为可用Map
  ///
  static bool isAvailableMap(Object? object) {
    if (object != null && object is Map && object.isNotEmpty) {
      return true;
    }
    return false;
  }

  ///
  /// 判断是否为可用List
  ///
  static bool isAvailableList(Object? object) {
    if (object != null && object is List && object.isNotEmpty) {
      return true;
    }
    return false;
  }

  ///
  /// 分割字符串
  /// 通过某个符号分割成数组
  ///
  static List<String> splitString(String string, String keyword) {
    List<String> list = string.split(keyword);
    return list;
  }

  ///
  /// 获取性别
  ///
  static String? getSex(int? string) {
    if (string == 1) {
      return '女';
    } else if (string == 2) {
      return '男';
    }
    return null;
  }

  /// 验证邮箱格式
  static bool isAvailableEmail(String? string) {
    if (isAvailableString(string)) {
      String regexEmail = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$";
      return RegExp(regexEmail).hasMatch(string!);
    }
    return false;
  }

  /// 验证URL格式
  static bool isAvailableURL(String? string) {
    if (isAvailableString(string)) {
      String regexEmail =
          "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#\$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#\$%^&*+?:_/=<>]*)?)";
      return RegExp(regexEmail).hasMatch(string!);
    }
    return false;
  }

  /// 判断是否为纯数字
  static bool isAllNumbers(String? string) {
    if (isAvailableString(string)) {
      String regex = "^[0-9]*\$";
      return RegExp(regex).hasMatch(string!);
    }
    return false;
  }

  /// 是否为指定长度的字母、数字及英文字符(例：6-20)
  static bool isSpecifiedLengthNumberOrAlphabet(String? string, {required int minLength, required int maxLength}) {
    if (isAvailableString(string)) {
      String regex = "^[0-9a-zA-Z \\`\\~\\!\\@\\#\\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-\\=\\[\\]\\{\\}\\\\\\|\\;\\'\\'\\:\\\"\\\"\\,\\.\\/\\<\\>\\?]{$minLength,$maxLength}\$";
      return RegExp(regex).hasMatch(string!);
    }
    return false;
  }

  /// 是否为指定长度的中文、字母、数字及英文字符
  static bool isSpecifiedLengthCharacterNumberOrAlphabet(String? string, int minLength, int maxLength) {
    if (isAvailableString(string)) {
      String regex =
          "^[\\u4e00-\\u9fa50-9a-zA-Z \\`\\~\\!\\@\\#\\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-\\=\\[\\]\\{\\}\\\\\\|\\;\\'\\'\\:\\\"\\\"\\,\\.\\/\\<\\>\\?]{$minLength,$maxLength}\$";
      return RegExp(regex).hasMatch(string!);
    }
    return false;
  }

  /// 获取指定长度随机字母+数字
  static String generateRandomString(int length) {
    final _random = Random();
    const _availableChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    final randomString = List.generate(length, (index) => _availableChars[_random.nextInt(_availableChars.length)]).join();
    return randomString;
  }

  ///
  /// 检查文本是否超出最大行数
  ///
  static bool textExceedMaxLines(String? text, TextStyle textStyle, int maxLine, double maxWidth) {
    TextSpan textSpan = TextSpan(text: text, style: textStyle);
    TextPainter textPainter = TextPainter(text: textSpan, maxLines: maxLine, textDirection: TextDirection.ltr);
    textPainter.layout(maxWidth: maxWidth);
    print(textPainter.height);
    if (textPainter.didExceedMaxLines) {
      return true;
    }
    return false;
  }

  static int? dymicToInt(dynamic dymic) {
    if (dymic is String && dymic != '') {
      return int.parse(dymic);
    }
    if (dymic is int) {
      return dymic;
    }
    if (dymic is double) {
      return dymic.toInt();
    }
    return null;
  }

  static String? dymicToString(dynamic dymic) {
    if (dymic is String) {
      return dymic;
    }
    if (dymic is int || dymic is double) {
      return dymic.toString();
    }
    return null;
  }

  static Uint8List encode(String s) {
    var encodedString = utf8.encode(s);
    var encodedLength = encodedString.length;
    var data = ByteData(encodedLength + 4);
    data.setUint32(0, encodedLength, Endian.big);
    var bytes = data.buffer.asUint8List();
    bytes.setRange(4, encodedLength + 4, encodedString);
    return bytes;
  }

  static Uint8List createUint8ListFromHexString(String hexString) {
    var result = Uint8List(hexString.length ~/ 2);
    for (var i = 0; i < hexString.length; i += 2) {
      var num = hexString.substring(i, i + 2);
      var byte = int.parse(num, radix: 16);
      result[i ~/ 2] = byte;
    }
    return result;
  }

  static String createHexStringFromUint8List(Uint8List bytes) {
    var result = StringBuffer();
    for (var i = 0; i < bytes.lengthInBytes; i++) {
      var part = bytes[i];
      result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
    }
    return result.toString();
  }

  static Uint8List unitList(String str) {
    int length = str.length;
    if (length % 2 != 0) {
      str = "0" + str;
      length++;
    }
    List<int> s = str.toUpperCase().codeUnits;
    Uint8List bArr = Uint8List(length >> 1);
    for (int i = 0; i < length; i += 2) {
      bArr[i >> 1] = ((s[i] << 4) | s[i + 1]);
    }
    return bArr;
  }
}
